package codec

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"gopkg.in/yaml.v3"
)

type JsonCodec struct{}

func (codec *JsonCodec) Marshal(v interface{}) ([]byte, error) {
	return json.Marshal(v)
}

func (codec *JsonCodec) Unmarshal(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}

type YamlCodec struct{}

func (codec *YamlCodec) Marshal(v interface{}) ([]byte, error) {
	return yaml.Marshal(v)
}

func (codec *YamlCodec) Unmarshal(data []byte, v interface{}) error {
	return yaml.Unmarshal(data, v)
}

type GobCodec struct{}

func (codec *GobCodec) Marshal(v interface{}) ([]byte, error) {
	buffer := bytes.Buffer{}

	en := gob.NewEncoder(&buffer)
	if err := en.Encode(v); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}

func (codec *GobCodec) Unmarshal(data []byte, v interface{}) error {
	buffer := bytes.NewBuffer(data)

	de := gob.NewDecoder(buffer)
	if err := de.Decode(v); err != nil {
		return err
	}
	return nil
}
